/*
 * Copyright 2015 泛泛o0之辈
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.base.prop;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class PropLoader {

    /**
     * 默认配置文件
     */
    public static final String CONFIG_FILE= "jfast-config.xml";

    private String configFile;
    private boolean found;
    private Map<String, String> propMap = new HashMap<String, String>();
    private Map<String, String> resourcesMap = new HashMap<String, String>();

    public void load() {
        SAXParserFactory sf = SAXParserFactory.newInstance();
        try {
            SAXParser parser = sf.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    super.startElement(uri, localName, qName, attributes);
                    if( qName.equals("resources")){
                        String location = "";
                        String mapping = "";
                        for (int i = 0; i < attributes.getLength(); i++) {
                            String attrName = attributes.getQName(i);
                            String attrValue = attributes.getValue(i);
                            if(attrName.equals("location"))
                                location = attrValue;
                            else if(attrName.equals("mapping"))
                                mapping = attrValue;
                        }
                        resourcesMap.put(apiPathFilter(location),apiPathFilter(mapping));
                    } else {
                        for (int i = 0; i < attributes.getLength(); i++) {
                            String attrName = attributes.getQName(i);
                            String attrValue = attributes.getValue(i);
                            propMap.put(attrName, attrValue);
                        }
                    }
                }
            };
            getConfigFile(PropLoader.class.getResource("/").getFile());
            parser.parse(new InputSource(configFile), handler);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getConfigFile(String path) throws UnsupportedEncodingException {
        File f = new File(URLDecoder.decode(path,"UTF-8"));
        if(f.exists() && f.isDirectory() && !found)
            for(String fileName:f.list())
                if(fileName.equals(CONFIG_FILE)) {
                    configFile = path + File.separator + CONFIG_FILE;
                    found = true;
                } else {
                    getConfigFile(path + File.separator + fileName);
                }
    }

    public Map<String, String> getPropMap() {
        return propMap;
    }

    public Map<String, String> getResourcesMap() {
        return resourcesMap;
    }

    private String apiPathFilter(String path) {
        return ("/" + path + "/").replaceAll("/+", "/");
    }
}
